//#include "stdafx.h"
#include <jni.h>
#include <btBulletDynamicsCommon.h>
 
// Rajout des bibliothèques
#pragma comment (lib, "BulletCollision.lib")
#pragma comment (lib, "BulletDynamics.lib")
#pragma comment (lib, "LinearMath.lib")

/* For JNI: C++ compiler need this */
extern "C" {

	jint Java_com_example_pong_MainActivity_test( JNIEnv*  env, jobject  thiz)
	{
		  // Algorithme de tri
		  btBroadphaseInterface* broadphase = new btDbvtBroadphase();

		  // Gestion des callbacks. Le dispatcher et la configuration
		  // permettent des réglages plus fins.
		  btDefaultCollisionConfiguration* collisionConfiguration = new btDefaultCollisionConfiguration();
		  btCollisionDispatcher* dispatcher = new btCollisionDispatcher(collisionConfiguration);
		  btSequentialImpulseConstraintSolver* solver = new btSequentialImpulseConstraintSolver;
		  btDiscreteDynamicsWorld* dynamicsWorld = new btDiscreteDynamicsWorld(dispatcher,broadphase,solver,collisionConfiguration);
		  dynamicsWorld->setGravity(btVector3(0,-10,0));

		  // Nos entités
		  btCollisionShape* groundShape = new btStaticPlaneShape(btVector3(0,1,0),1);
		  btCollisionShape* fallShape = new btSphereShape(1);

		  // On instancie notre sol en tant qu’entité statique.
		  btDefaultMotionState* groundMotionState = new btDefaultMotionState(btTransform(btQuaternion(0,0,0,1), btVector3(0,-1,0)));
		  btRigidBody::btRigidBodyConstructionInfo groundRigidBodyCI(0, groundMotionState, groundShape, btVector3(0,0,0));
		  btRigidBody* groundRigidBody = new btRigidBody(groundRigidBodyCI);
		  dynamicsWorld->addRigidBody(groundRigidBody);

		  // On instancie notre sphère et on lui applique une inertie.
		  btDefaultMotionState* fallMotionState = new btDefaultMotionState(btTransform(btQuaternion(0,0,0,1),btVector3(0,50,0)));
		  btScalar mass = 1;
		  btVector3 fallInertia(0,0,0);
		  fallShape->calculateLocalInertia(mass,fallInertia);
		  btRigidBody::btRigidBodyConstructionInfo fallRigidBodyCI(mass,fallMotionState,fallShape,fallInertia);
		  btRigidBody* fallRigidBody = new btRigidBody(fallRigidBodyCI);
		  dynamicsWorld->addRigidBody(fallRigidBody);

		  // On lance la simulation pendant 300 frames.
		  btTransform trans;
		  for (int i=0 ; i < 100 ; i++)
		  {
		    dynamicsWorld->stepSimulation(1/60.f,10);
		  }

		  fallMotionState->getWorldTransform(trans);
		  int res = trans.getOrigin().getY();

		  // On libere nos entités…
		  dynamicsWorld->removeRigidBody(fallRigidBody);
		  delete fallRigidBody->getMotionState();
		  delete fallRigidBody;
		  dynamicsWorld->removeRigidBody(groundRigidBody);
		  delete groundRigidBody->getMotionState();
		  delete groundRigidBody;
		  delete fallShape;

		  delete groundShape;
		  // … et tous les éléments de Bullet Physics.
		  delete dynamicsWorld;
		  delete solver;
		  delete collisionConfiguration;
		  delete dispatcher;
		  delete broadphase;


		  return res;
	}

}
